package com.isoft.service.impl;

import com.isoft.entity.DfmeCfceEntity;
import com.isoft.mapper.DfmeCfceMapper;
import com.isoft.service.DfmeCfceService;
import com.isoft.util.XmlParserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Service
public class DfmeCfceServiceImpl implements DfmeCfceService {
    private static final Logger logger = LoggerFactory.getLogger(DfmeCfceServiceImpl.class);

    @Autowired
    private DfmeCfceMapper dfmeCfceMapper;

    @Autowired
    private XmlParserUtil xmlParserUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(MultipartFile file) throws IOException {
        String xmlContent = new String(file.getBytes(), StandardCharsets.UTF_8);
        logger.info("Processing CFCE XML file: {}, size: {} bytes",
                file.getOriginalFilename(), file.getSize());
        return parseAndSave(xmlContent);
    }

    @Override
    public void parseAndSave(DfmeCfceEntity entity) {
        processFlightData(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(String xmlContent) {
        try {
            if (xmlContent == null || xmlContent.trim().isEmpty()) {
                throw new IllegalArgumentException("XML content is empty");
            }

            DfmeCfceEntity entity = xmlParserUtil.parseXml(xmlContent, DfmeCfceEntity.class);

            if (entity == null || entity.getDflt() == null) {
                throw new IllegalArgumentException("Invalid XML structure");
            }

            processFlightData(entity);

            return "Flight aircraft change data processed successfully. Flight ID: " + entity.getDflt().getFlightId();
        } catch (Exception e) {
            logger.error("CFCE XML processing failed", e);
            throw new RuntimeException("Failed to process CFCE XML: " + e.getMessage());
        }
    }

    private void processFlightData(DfmeCfceEntity entity) {
        try {
            // 1. 插入元数据
            dfmeCfceMapper.insertMeta(entity);

            // 2. 插入航班基础信息
            dfmeCfceMapper.insertFlightBase(entity);

            // 3. 插入飞机变更信息
            dfmeCfceMapper.insertAircraft(
                    entity.getDflt().getFlightId(),
                    entity.getDflt().getAircraftType(),
                    entity.getDflt().getAircraftNumber());

            logger.info("Successfully processed flight data. Meta ID: {}, Flight ID: {}",
                    entity.getMeta().getMsgId(),
                    entity.getDflt().getFlightId());
        } catch (Exception e) {
            logger.error("Error processing flight data", e);
            throw new RuntimeException("Database operation failed: " + e.getMessage());
        }
    }
}